# prerequisite: GOROOT and GOARCH must be defined

# defines $(GC) (compiler), $(LD) (linker) and $(O) (architecture)
include $(GOROOT)/src/Make.$(GOARCH)

ifndef GOBIN
    YACC=goyacc
else
    YACC=$(GOBIN)/goyacc
endif

# name of the package (library) being built
TARG=gb

# source files in package
DEPGRAPHFILES=\
	src/gb/depgraph/depgraph.go \

RECPFILES=\
	src/gb/recipes/recipes.go \
	src/gb/recipes/invocation_acc.go \
	src/gb/recipes/dependency.go \

PACKAGES=\
	_obj/gb/depgraph.a \
	_obj/gb/invocation.a \
	_obj/gb/gbparser.a \
	_obj/gb/recipe.a \
	_obj/gb/recipes.a \
	_obj/gb/recipes/builtin.a \
	_obj/gb/tools.a \

# build "main" executable
$(TARG): packages _obj/gb/gb.$O
	$(LD) -L_obj -o $(TARG) _obj/gb/gb.$O
	@echo "Done. Executable is: $(TARG)"

.PHONY: clean
clean: testpackage-clean
	rm -rf _obj gb.$O

.PHONY: packages
packages: $(PACKAGES)

.PHONY: testpackage-clean
testpackage-clean:
	rm -rf _test 6.out

.PHONY: testpackage
testpackage: _test/gb/gbparser.a

.PHONY: importpath
importpath:
	@echo gb/gbparser

.PHONY: test
test:
	GL="$(LD) -L_test -L_obj" gotest .

# dependencies
_obj/gb/parser.$O: _obj/gb/recipe.a _obj/gb/invocation.a
_test/gb/parser.$O: _obj/gb/recipe.a _obj/gb/invocation.a

_obj/gb/recipes.$O: _obj/gb/recipe.a _obj/gb/invocation.a _obj/gb/tools.a _obj/gb/recipes/builtin.a
_obj/gb/gbparser.$O: _obj/gb/recipe.a _obj/gb/invocation.a _obj/gb/tools.a
_obj/gb/recipe.$O: _obj/gb/tools.a _obj/gb/invocation.a
_obj/gb/invocation.$O: _obj/gb/tools.a

# packages
_test/gb/gbparser.a: _test/gb/gbparser.$O
	@mkdir -p _test/
	rm -f $@
	gopack grc $@ $<

_obj/%.a: _obj/%.$O
	rm -rf $@
	gopack grc $@ $<

# compile
_obj/gb/depgraph.$O: $(DEPGRAPHFILES)
	@mkdir -p _obj/gb
	$(GC) -I_obj -o $@ $(DEPGRAPHFILES)

_obj/gb/gbparser.$O: _obj/gb/gbparser/parser.go
	@mkdir -p _obj/gb
	$(GC) -I_obj -o $@ $<
	
_obj/gb/recipes.$O: $(RECPFILES)
	@mkdir -p _obj/gb/parser
	$(GC) -I_obj -o $@ $(RECPFILES)

_test/gb/gbparser.$O: _obj/gb/gbparser/parser.go src/gb/gbparser/parser_test.go
	@mkdir -p _test/gb
	$(GC) -I_obj -o $@ _obj/gb/gbparser/parser.go src/gb/gbparser/parser_test.go

_obj/gb/recipes/builtin.$(O): src/gb/recipes/builtin/builtin.go
	@mkdir -p _obj/gb/recipes
	$(GC) -I_obj -o $@ $<

_obj/gb/%.$(O): src/gb/%/*.go
	@mkdir -p _obj/gb
	$(GC) -I_obj -o $@ $<

# goyacc
_obj/gb/gbparser/parser.go: src/gb/gbparser/parser.y
	@mkdir -p _obj/gb/gbparser
	$(YACC) -o $@ $<


